package com.xiaoyi.springboot.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoyi.springboot.config.ResponseHelper;
import com.xiaoyi.springboot.config.ResponseModel;
import com.xiaoyi.springboot.entity.SysUser;
import com.xiaoyi.springboot.service.SysUserRoleService;
import com.xiaoyi.springboot.service.SysUserService;
import com.xiaoyi.springboot.shiro.JwtUtil;
import com.xiaoyi.springboot.util.PasswordUtil;
import com.xiaoyi.springboot.util.StringUtils;
import com.xiaoyi.springboot.vo.SystemUserReqVo;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xiaoyi
 * @since 2021-03-18
 */
@RestController
@RequestMapping("/sys-user")
public class SysUserController {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserRoleService userRoleService;



    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @RequiresRoles(value = "systemadmin")
    public ResponseModel<Object> add(@RequestBody SysUser user) {
        try {
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysUser::getUsername,user.getUsername());
            List<SysUser> list = sysUserService.list(queryWrapper);
            if(list.size()>1){
                return ResponseHelper.validationFailure("登录名重复");
            }
            user.setCreateTime(new Date());//设置创建时间
            String salt = StringUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag(0);
            sysUserService.addUser(user);

            return ResponseHelper.buildResponseModel("添加成功");
        } catch (Exception e) {
            return ResponseHelper.validationFailure("添加失败");
        }
    }

    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    @RequiresRoles(value = "systemadmin")
    //@RequiresPermissions("user:edit")
    public ResponseModel<String> edit(@RequestBody JSONObject jsonObject) {
        ResponseModel<SysUser> result = new ResponseModel<SysUser>();
        try {
            SysUser sysUser = sysUserService.getById(jsonObject.getString("id"));
            if(sysUser==null) {
                return ResponseHelper.validationFailure("未找到对应实体");
            }else {
                SysUser user = JSON.parseObject(jsonObject.toJSONString(), SysUser.class);
                user.setUpdateTime(new Date());
                //String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), sysUser.getSalt());
                user.setPassword(sysUser.getPassword());
                String roles = jsonObject.getString("selectedroles");
                String departs = jsonObject.getString("selecteddeparts");

               return  ResponseHelper.buildResponseModel("修改成功");
            }
        } catch (Exception e) {

            return ResponseHelper.validationFailure("修改失败");
        }
    }

    /**
     * 删除用户
     */
    @RequiresRoles(value = "systemadmin")
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE)
    public ResponseModel<?> delete(@RequestParam(name="id",required=true) String id) {
        return  ResponseHelper.buildResponseModel("删除用户成功");
    }
    @PostMapping("/page")
    @RequiresRoles(value = "systemadmin")
    public ResponseModel<Page<SysUser>> page(@RequestBody SystemUserReqVo systemUserReqVo,
                                      HttpServletRequest request) {

        String userName = JwtUtil.getUserNameByToken();
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getStatus,1);
        queryWrapper.eq(SysUser::getDelFlag,0);
        queryWrapper.ne(SysUser::getUsername,userName);
        queryWrapper.orderBy(true,false,SysUser::getCreateTime);
        Page<SysUser> sysUserPage = new Page<>(systemUserReqVo.getPageNum(), systemUserReqVo.getPageSize());
        Page<SysUser> page = sysUserService.page(sysUserPage, queryWrapper);
        return ResponseHelper.buildResponseModel(page);

    }
}
